package com.myhdg.school.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.widget.TextView;
import android.widget.Toast;

import com.myhdg.school.R;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;

import okhttp3.Call;

public class LoginDialog extends Dialog {
    private TextView loginState;

    private String id;//学号
    private String password;//密码
    private String verification;//验证码

    //验证码获取链接
    private String codeUrl = "http://61.139.105.138/CheckCode.aspx";
    //登录链接
    private String loginUrl = "http://61.139.105.138/default2.aspx";
    //登录input隐式参数
    private String viewstate = "dDwyODE2NTM0OTg7Oz5xwfyqX7AwPfxgTOgX+8Gxg6Trhw==";


    public static final int LOGIN_SUCCESS = 0x00;//登录成功
    public static final int LOGIN_FAIL_ID = 0x01;//学号错误
    public static final int LOGIN_FAIL_PASSWORD = 0x02;//密码错误
    public static final int LOGIN_FAIL_VERIFICATION = 0x03;//验证码错误
    public static final int LOGIN_FAIL_INTERNET = 0x04;//网络错误
    public static final int LOGIN_FAIL_OTHER = 0x05;//其他错误

    private LoginListener loginListener;

    public LoginDialog(@NonNull Context context, LoginListener loginListener, String id, String password, String verification) {
        super(context);
        this.loginListener = loginListener;
        this.id = id;
        this.password = password;
        this.verification = verification;

        //点击提示框外面是否取消提示框
        setCanceledOnTouchOutside(false);
        //点击返回键是否取消提示框
        setCancelable(false);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_login);

        loginState = findViewById(R.id.loginState);
        loginState.setText("正在登录...");

        login();
    }

    private void login() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //jsoup联网获取viewstate
                    Document ZFDoc = null;
                    try {
                        ZFDoc = Jsoup.
                                connect("http://61.139.105.138/default2.aspx")
                                .cookie("Cookie","ASP.NET_SessionId=w3m4lm55etch0nqdyd3l052m; safedog-flow-item=")
                                .header("Referer", "http://61.139.105.138/default2.aspx")
                                .get();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String newViewstate=ZFDoc.select("input[name=__VIEWSTATE]").val();
                    viewstate=newViewstate;
                System.out.println(viewstate);

                //登录正方
                try {
                    //登录正方教务
                    OkHttpUtils.post().url(loginUrl)
                            .addParams("__VIEWSTATE", viewstate)
                            .addParams("txtUserName", id)
                            .addParams("TextBox2", password)//密码
                            .addParams("txtSecrverificationCode", verification) //验证码
                            .addParams("RadioButtonList1", "%D1%A7%C9%FA")
                            .addParams("Button1", "")
                            .addParams("lbLanguage", "")
                            .addParams("hidPdrs", "")
                            .addParams("hidsc", "")
                            .addHeader("Host", "61.139.105.138")
                            .addHeader("Origin","http://61.139.105.138")
                            .addHeader("Content-Type","application/x-www-form-urlencoded")
                            .addHeader("Referer", "http://61.139.105.138/default2.aspx")
                            .addHeader("Cookie", "ASP.NET_SessionId=w3m4lm55etch0nqdyd3l052m; safedog-flow-item=")
                            .build().connTimeOut(5000).execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            //请求成功，response就是得到的html文件（网页源代码）
                            //System.out.println(response);
                            System.out.println("onResponse");

                            if (response.contains("验证码不正确")) {
                                //如果源代码包含“验证码不正确”
                                stateHandler.sendEmptyMessage(LOGIN_FAIL_VERIFICATION);//通知DialogUI线程更改状态信息
                            } else if (response.contains("密码错误")) {
                                //如果源代码包含“密码错误”
                                System.out.println("密码错误");
                                stateHandler.sendEmptyMessage(LOGIN_FAIL_PASSWORD);//通知DialogUI线程更改状态信息
                            } else if (response.contains("用户名不存在")) {
                                //如果源代码包含“用户名不存在”
                                stateHandler.sendEmptyMessage(LOGIN_FAIL_ID);//通知DialogUI线程更改状态信息
                                System.out.println("用户名不存在");
                            } else if (response.contains("error")){
                                Toast.makeText(getContext(),"网络错误",Toast.LENGTH_LONG).show();

                            }else if(response.contains("验证码不能为空")){
                                Toast.makeText(getContext(),"验证错误",Toast.LENGTH_LONG).show();
                            } else {
                                //登录成功
                                System.out.println(response);
                                stateHandler.sendEmptyMessage(LoginDialog.LOGIN_SUCCESS);//通知DialogUI线程更改状态信息
                                try {
                                    Thread.sleep(2000);//Dialog动画多显示一会儿
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                    LoginDialog.this.dismiss();
                                }
                                loginListener.getLoginState(LOGIN_SUCCESS);//状态信息反馈回登陆界面
                            }
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
                LoginDialog.this.dismiss();
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private final Handler stateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == LOGIN_SUCCESS) {
                loginState.setText("登陆成功！");
            } else if (msg.what == LOGIN_FAIL_ID) {
                loginState.setText("学号有误！");
            } else if (msg.what == LOGIN_FAIL_PASSWORD) {
                loginState.setText("密码错误！");
            } else if (msg.what == LOGIN_FAIL_VERIFICATION) {
                loginState.setText("验证码错误！");
            } else if (msg.what == LOGIN_FAIL_INTERNET) {
                loginState.setText("网络错误！");
            } else if (msg.what == LOGIN_FAIL_OTHER) {
                loginState.setText("其他错误！");
            }
        }
    };

    //=====登录状态监听器=====
    public interface LoginListener {
        void getLoginState(int state);
    }
}
